package com.jin.webvideo.websocket.shareroom;

import com.jin.webvideo.websocket.shareroom.entity.RoomUtil;
import org.springframework.stereotype.Component;
import java.util.*;

@Component
public class ShareRoomManager {
    private Map<Long, ShareRoom> roomMap = new HashMap<>();
    private static final long MAXNUM = 65535;
    private long roomNum = 1000;

    /**
     * 创建房间
     * @param account
     * @return
     */
    public long createRoom(String account){
        synchronized (this){
            if (roomMap.keySet().size() > MAXNUM){
                closeAll();
            }
            while (roomMap.containsKey(roomNum)){
                roomNum ++;
                if (roomNum < 0){
                    roomNum = 1000;
                }
            }
            roomMap.put(roomNum, new ShareRoom(roomNum, account));
        }
        return roomNum;
    }

    /**
     * 列出所有房间
     * @return
     */
    public List<ShareRoom> listAll() {
        List<ShareRoom> list = new ArrayList<>();
        for (long key : roomMap.keySet()){
            list.add(roomMap.get(key));
        }
        return list;
    }

    /**
     * 通过roomID查找房间
     * @param roomId
     * @return
     */
    public ShareRoom findByRoomId(long roomId){
        ShareRoom room = roomMap.get(roomId);
        if (room != null && room.isClose()){
            return null;
        }
        return room;
    }

    /**
     * 通过roomOwner查找房间
     * @param roomid
     * @return
     */
    // roomNo 与 房间 owner绑定
    public ShareRoom findByRoomOwner(long roomid){
        ShareRoom room = roomMap.get(roomid);
        if (room != null && room.isClose()){
            return null;
        }
        return room;
    }

    /**
     * 关闭所有房间
     */
    public void closeAll(){
        for (long roomid : roomMap.keySet()){
            closeRoom(roomMap.get(roomid));
        }
    }

    /**
     * 关闭房间
     * @param room
     */
    public void closeRoom(ShareRoom room){
        RoomUtil.close(room);
        roomMap.remove(room.getRoomId());
    }
}
